import React, {Component} from 'react';
import NavigationBar from '../../Common/NavigationBar/NavigationBar.jsx';
import DialogNative from '../../Common/Dialog/Dialog.jsx';
import DialogHeader from '../../Common/Dialog/DialogHeader.jsx';
import DialogBody from '../../Common/Dialog/DialogBody.jsx';
import DialogFooter from '../../Common/Dialog/DialogFooter.jsx';
import WeUI from 'react-weui';
import {CSS} from "../styles/meetingRoom.css";
import $ from 'jquery';
const {
    CellsTitle,
    Cells,
    Cell,
    CellBody,
    CellFooter,
    Toptips,
    Toast,
} = WeUI;
//算高
var meetingRooms = [{}, {}, {}];
var periods = [{}, {}];
let show_day = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
class BookingRoomItem extends Component {
    constructor(props) {
        super(props);
        this.showDetail = this.showDetail.bind(this);
        this.closeDialog = this.closeDialog.bind(this);
        this.getDisplayAmountByStatus = this.getDisplayAmountByStatus.bind(this);
        this.getMeetingDetailFooter = this.getMeetingDetailFooter.bind(this);
        this.callWxPay = this.callWxPay.bind(this);
        this.state = {
            showDetailFlag: false,
            showToast: false,
            resetPwdText: "没收到？重新发送",
            sendPwdSuccess : false,
            meetingRoomPayType:false,
            selectPayType:null,
        };
    }



    //获取状态
    getBookingRoomStatus(bookingRoomItem) {
        if(bookingRoomItem.payStatusId === 1) {
            return <div className="status-unpay">待支付</div>;
        } else if(bookingRoomItem.payStatusId === 3) {
            return <div className="status-done">已取消</div>;
        }
        let statusName = null;
        console.log("bookingRoomItem.meetingStatusId" + bookingRoomItem.meetingStatusId);
        switch (bookingRoomItem.meetingStatusId) {
            case 1 :
                statusName = <div className="status-ready">未开始</div>;
                break;
            case 2 :
                statusName = <div className="status-meeting">会议中</div>;
                break;
            case 3 :
                statusName = <div className="status-done">已结束</div>;
                break;
            case 4 :
                statusName = <div className="status-done">已取消</div>;
                break;
            default:
                statusName = <div className="status-ready">未开始</div>;
                break;
        }
        return statusName;
    }

    closeDialog() {
        this.setState({
            showDetailFlag: false,
            meetingRoomPayType:false,
        });
        return;
    }

    showDetail() {
        this.setState({
            showDetailFlag: true
        });
        return;
    }



    //微信支付
    callWxPay(meetingRoomOrderId) {
        if (meetingRoomOrderId) {
            let getMeetingRoomPayInfo =  "/wxpay/createOrder/MeetingRoom?" + "meetingRoomOrderId=" + meetingRoomOrderId;
            fetch(getHost() + getMeetingRoomPayInfo, {
                credentials: "include"
            }).then(res => res.json()).then(json=> {
                if (json.success) {
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest',
                        json.data,
                        function (res) {
                            //不管失败或者成果，都会跳转到历史订单页面
                            if (res.err_msg == "get_brand_wcpay_request:ok") {// 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                location.reload();
                                return;
                            } else {  //支付失败或者取消，直接跳转到：合约信息中。
                                markDataRequestFlag();
                                location.reload();
                                return;
                            }
                        }
                    );
                } else {
                    this.showSelectPeriodError("网络不给力，请重试！");
                    return;
                }
            }).catch(e => {
                this.showSelectPeriodError("网络不给力，请重试！");
                return;
            });

        } else {
            this.showSelectPeriodError("网络不给力，请重试！");
            return;
        }
    }


    //取消会议室预约
    cancelOrder(e) {
        console.log("cancel orders");
        let cancelOrderUrl =  "/MeetingRoom/booking/order/cancel?meetingRoomOrderId=" + this.props.bookingRoomItem.meetingRoomOrderId;
        fetch(getHost() + cancelOrderUrl, {
            credentials: "include",
            method: "POST"
        }).then(res => res.json()).then(json => {
            if (json.success) {
                console.log("cancel successfully.");
                location.reload();
            } else {
                console.log("error on cancel order");
            }
        }).catch(e => {
            console.log("error on cancel order");
        });
    }


    //支付订单
    callPayOrder(type) {
        console.log("call weixin pay orders");
        if(type === 1){ //个人支付
            this.callWxPay(this.props.bookingRoomItem.meetingRoomOrderId);
        }else{//企业支付




        }
    }


    // // 选择支付方式
    // selectPayTypeClick(type){
    //     this.setState({selectPayType:type,meetingRoomPayType:true});
    // }



    //渲染界面
    getDisplayAmountByStatus() {
        // let dialogBtns = <div className="btnGroup">
        //     <div className="floatLeft btn cancel" onClick={this.cancelOrder}>取消预约</div>
        //     <div className="floatLeft btn confirm" onClick={this.callPayOrder}>确认支付</div>
        // </div>;
        let shouldPayAmount = {};
        let meetingRoomOrder = this.props.bookingRoomItem;

        let payAmountBox = null, opValue = null, payAmountCol = null, payType = null;
        if (meetingRoomOrder.payStatusId === 1) { //会议未支付，引导用户去支付
            Object.assign(shouldPayAmount, {fontSize: '4rem', color: "#FFD286", lineHeight: "4rem"});
            if(meetingRoomOrder.useRechargePackage){ //企业支付
                payType = <tr>
                    <td className="detail-header">支付方式：</td>
                    <td>企业支付</td>
                </tr>;
                payAmountBox = <tr>
                    <td className="detail-header">抵扣时间：</td>
                    <td></td>
                </tr>;
                payAmountCol = <tr>
                    <td></td>
                    <td style={shouldPayAmount}>
                        <div>{meetingRoomOrder.amount / meetingRoomOrder.meetingRoomVo.hourlyPrice}小时</div>
                    </td>
                </tr>
                opValue = <tr>
                    <td colSpan="2">
                        <div className="btnGroup">
                            <div className="floatLeft btn cancel" onClick={this.cancelOrder.bind(this,2)}>取消预约</div>
                            <div className="floatLeft btn confirm" onClick={this.callPayOrder.bind(this,2)}>确认抵扣</div>
                        </div>
                    </td>
                </tr>;
            }else{//个人支付
                payType = <tr>
                    <td className="detail-header">支付方式：</td>
                    <td>个人支付</td>
                </tr>;
                payAmountBox = <tr>
                    <td className="detail-header">支付费用：</td>
                    <td></td>
                </tr>;
                payAmountCol = <tr>
                    <td></td>
                    <td style={shouldPayAmount}>
                        <div>¥{meetingRoomOrder.amount}</div>
                    </td>
                </tr>
                opValue = <tr>
                    <td colSpan="2">
                        <div className="btnGroup">
                            <div className="floatLeft btn cancel" onClick={this.cancelOrder.bind(this,1)}>取消预约</div>
                            <div className="floatLeft btn confirm" onClick={this.callPayOrder.bind(this,1)}>确认支付</div>
                        </div>
                    </td>
                </tr>;
            }
        } else if (meetingRoomOrder.payStatusId === 2 && meetingRoomOrder.meetingStatusId <= 2) { //会用未开始或者使用中
            opValue = <tr>
                <td colSpan="2" className="meeting-in">
                    <div className="password-div">
                        <div className="meeting-pwd"><img src="/iot-meeting/assets/images/meetingRoom/lock-icon.png" className="lock-icon"/>员工可通过扫脸进入会议室</div>
                    </div>
                </td>
            </tr>;
        } else if (meetingRoomOrder.meetingStatusId === 3) {  //会议已经结束

            if(meetingRoomOrder.useRechargePackage) { //企业支付
                payAmountBox = <tr>
                    <td className="detail-header">抵扣时间：</td>
                    <td style={shouldPayAmount}>
                        <div>{meetingRoomOrder.bookLength}小时</div>
                    </td>
                </tr>;
                payType = <tr>
                    <td className="detail-header">支付方式：</td>
                    <td>企业支付</td>
                </tr>
            }else{//个人支付
                payAmountBox = <tr>
                    <td className="detail-header">支付费用：</td>
                    <td style={shouldPayAmount}>
                        <div>¥{meetingRoomOrder.amount}</div>
                    </td>
                </tr>;
                payType = <tr>
                    <td className="detail-header">支付方式：</td>
                    <td>个人支付</td>
                </tr>
            }
            opValue = <tr>
                <td colSpan="2">
                    <div><img src="/iot-meeting/assets/images/meetingRoom/order_finish_icon.png" className="disabled-img"/></div>
                </td>
            </tr>;
        } else if (meetingRoomOrder.meetingStatusId === 4) { //用户取消了会议
            if(meetingRoomOrder.useRechargePackage){ //企业支付
                payAmountBox = <tr>
                    <td className="detail-header">抵扣时间：</td>
                    <td style={shouldPayAmount}>
                        <div>{meetingRoomOrder.bookLength}小时</div>
                    </td>
                </tr>;
                payType = <tr>
                    <td className="detail-header">支付方式：</td>
                    <td>企业支付</td>
                </tr>
            }else{//个人支付
                payAmountBox = <tr>
                    <td className="detail-header">支付费用：</td>
                    <td style={shouldPayAmount}>
                        <div>¥{meetingRoomOrder.amount}</div>
                    </td>
                </tr>;
                payType = <tr>
                    <td className="detail-header">支付方式：</td>
                    <td>个人支付</td>
                </tr>
            }
            opValue = <tr>
                <td colSpan="2">
                    <div><img src="/iot-meeting/assets/images/meetingRoom/order_cancel_icon.png" className="disabled-img"/></div>
                </td>
            </tr>;
        }

        return {payAmountBox: payAmountBox, opValue: opValue, payAmountCol: payAmountCol,payType:payType};
    }

    getMeetingDetailFooter() {
        let meetingRoomOrder = this.props.bookingRoomItem;
        if (meetingRoomOrder.payStatusId === 1) {
            return <div>
                <div>会议室使用规则：</div>
                <div>请请尽量准时开始，准时结束会议，谢谢配合</div>
            </div>;
        } else if (meetingRoomOrder.payStatusId === 2 && meetingRoomOrder.meetingStatusId <= 3) {
            return <div>
                <div>订单号：{meetingRoomOrder.orderNum}</div>
                <div>预约时间：{convertTimestampToStringWithDate(meetingRoomOrder.createTime)}</div>
                <div>支付时间：{meetingRoomOrder.payTime} </div>
            </div>;
        } else if (meetingRoomOrder.meetingStatusId === 4) {
            return <div>
                <div>订单号：{meetingRoomOrder.orderNum}</div>
                <div>预约时间：{convertTimestampToStringWithDate(meetingRoomOrder.createTime)}</div>
                <div>支付已取消</div>
            </div>;
        } else {
            return null;
        }
    }

    getShowTime(dateTimeString) {
        if(dateTimeString) {
            let dateTimeArr = dateTimeString.split(" ");
            if(dateTimeArr && dateTimeArr.length == 2) {
                let time = dateTimeArr[1];
                return time.substring(0, time.lastIndexOf(":"));
            } else {
                return dateTimeString;
            }
        } else {
            return dateTimeString;
        }
    }


    render() {
        let amountByStatus = this.getDisplayAmountByStatus();
        let meetingRoomOrder = this.props.bookingRoomItem;
        // {show_day[new Date(meetingRoomOrder.bookingDate).getDay()-1]}展示星期几
        let bookingShowTime =
            <span>{meetingRoomOrder.bookingDate} {this.getShowTime(meetingRoomOrder.startTime) + "-" + this.getShowTime(meetingRoomOrder.endTime)}</span>;
        let meetingDetailFooter = this.getMeetingDetailFooter();
        return (
            <div className="bookingRoomItemBox" onClick={this.showDetail}>
                <div></div>
                <div className="floatLeft">
                    <div>{bookingShowTime}</div>
                    <div className="teamName">{meetingRoomOrder.bookTeamName}</div>
                </div>
                <div className="floatRight">
                    {meetingRoomOrder.useRechargePackage?<div className="amountStyle">{meetingRoomOrder.bookLength}h</div>: <div className="amountStyle">¥{meetingRoomOrder.amount}</div>}
                    {this.getBookingRoomStatus(this.props.bookingRoomItem)}</div>
                <div className="clearFloat"></div>

                <DialogNative show={this.state.showDetailFlag} close={this.closeDialog}>
                    <DialogHeader>预约记录</DialogHeader>
                    <DialogBody meetingStatus={meetingRoomOrder.meetingStatusId}>
                        <table style={{width:"100%"}}>
                            <tbody>
                            <tr>
                                <td className="detail-header">开会时间：</td>
                                <td>{bookingShowTime}</td>
                            </tr>
                            <tr>
                                <td className="detail-header">使用企业：</td>
                                <td>{meetingRoomOrder.bookTeamName}</td>
                            </tr>
                            <tr>
                                <td className="detail-header">订单号：</td>
                                <td>{meetingRoomOrder.orderNum}</td>
                            </tr>
                            <tr>
                                <td className="detail-header">会议室：</td>
                                <td>{meetingRoomOrder.meetingRoomVo.meetingRoomSerialNum + meetingRoomOrder.meetingRoomVo.meetingRoomName}</td>
                            </tr>
                            <tr>
                                <td className="detail-header">会议地点：</td>
                                <td>{meetingRoomOrder.meetingRoomVo.buildingName + meetingRoomOrder.meetingRoomVo.floorName}</td>
                            </tr>
                            <tr>
                                <td className="detail-header">容纳人数：</td>
                                <td>{meetingRoomOrder.meetingRoomVo.seatNum}人</td>
                            </tr>
                            {amountByStatus.payType}
                            {amountByStatus.payAmountBox}
                            {amountByStatus.payAmountCol}
                            {amountByStatus.opValue}
                            </tbody>
                        </table>
                    </DialogBody>
                    <DialogFooter>
                        {meetingDetailFooter}
                    </DialogFooter>
                </DialogNative>
            </div>
        );
    }
}

class BookingRoomList extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let bookingRoomArr = [];
        (this.props.rooms && this.props.rooms.length > 0 ) && this.props.rooms.forEach((item, index) => {
            bookingRoomArr.push(<BookingRoomItem bookingRoomItem={item} key={index}/>);
        });
        if (bookingRoomArr.length === 0) {
            bookingRoomArr = <div className="emptyList">暂无记录！</div>;
        }

        return (<div>
            {bookingRoomArr}
        </div>)
    }
}

let screenWidth = $(window).width();
let screenHeight = $(window).innerHeight();
let baseFontSize = 10 * screenWidth / 375;
const meetingRoomOrderList = [];
export default class MeetingRoomHistory extends Component {
    constructor(props) {
        super(props);
        this.LeftClick = this.LeftClick.bind(this);
        this.RightClick = this.RightClick.bind(this);
        this.showExpire = this.showExpire.bind(this);
        this.getList = this.getList.bind(this);
        let teamId = this.props.location.query.teamId;
        console.log("TeamId:" + teamId);
        this.state = {
            meetingRoomOrderList:[],
            showExpire: false,
            showLoading: true,
            teamId : teamId,
            isCompanyAdmin:this.props.location.query.isCompanyAdmin,
            teamName:this.props.location.query.teamName,
        };
    }

    componentWillMount() {
    }

    componentDidMount() {
        this.getList(false);
    }

    LeftClick() {
        if (this.state.showExpire){
            this.getList(false);
            location.hash = "/MeetingRoomHistory?teamId=" + this.state.teamId + "&isCompanyAdmin=" + this.state.isCompanyAdmin + "&teamName=" +this.state.teamName;
        } else {
            location.hash = "/UserCenter";
        }
    }

    RightClick() {
        location.hash = "/MeetingRoom";
        return;
    }

    getList(showExpire) {
        let listUrl =  "/MeetingRoom/booking/order/list/";
        let teamIdFilter = (this.state.teamId > 0) ? ("?teamId=" + this.state.teamId) :  "";
        if(showExpire) {
            listUrl += "inactive";
        } else {
            listUrl += "active";
        }
        console.log("teamIdFilter:" + teamIdFilter);
        fetch(getHost() + listUrl + teamIdFilter, {
            credentials: "include"
        }).then(res => res.json()).then(json=> {
            if (json.success) {
                this.setState({
                    meetingRoomOrderList: json.data.returnList,
                    showExpire: showExpire,
                    showLoading: false
                });
            } else {
                console.log("error on get RoomList");
                this.setState({
                    meetingRoomOrderList: [],
                    showExpire: showExpire,
                    showLoading: false
                });
            }
        }).catch(e=> {
            this.setState({
                meetingRoomOrderList: [],
                showExpire: showExpire,
                showLoading: false
            });
        });
    }
    showExpire() {
        this.getList(true);
        return;
    }

    meetingPayTimeList(){
        location.hash = "/MeetingRoomTimeUse?teamName="+this.state.teamName+"";
    }

    render() {
        let cell = "";
        let remainHeight = "";
        if(this.state.showExpire){
            cell = "";
            remainHeight = screenHeight - (0) * baseFontSize  + "px";
        }else{
            if(this.state.isCompanyAdmin === "true" || this.state.isCompanyAdmin === true){
                cell =  <Cells style={{background: "white",marginTop:"0px",height:"4.2rem"}}>
                    <Cell access onClick={this.meetingPayTimeList.bind(this)}>
                        <CellBody>
                            <div className="create_visitor_title">查看会议室加油包</div>
                        </CellBody>
                        <CellFooter/>
                    </Cell>
                </Cells>;
                remainHeight = screenHeight - (4 + 4.2 + 5.6) * baseFontSize  + "px";
            }else{
                cell = "";
                remainHeight = screenHeight - (4 + 5.6) * baseFontSize  + "px";
            }
        }
        return (
            <div style={{height:'100%', width:'100%'}}>
                <NavigationBar Title="预约记录" LeftBar="true" LeftTitle="返回"
                               LeftIconSrc="/iot-meeting/assets/images/common/nav_back_icon.png" LeftClick={this.LeftClick}
                               RightBar="true" RightTitle="去预约" RightClick={this.RightClick}/>

                {cell}
                <div style={{height:remainHeight,overflow:"scroll"}}>
                    <BookingRoomList rooms={this.state.meetingRoomOrderList}/>
                </div>
                {!this.state.showExpire ?
                <div className="bookedHistoryLink" onClick={this.showExpire}>
                    <div><img src="/iot-meeting/assets/images/meetingRoom/expire_meeting_order.png"
                              style={{height: '2.5rem',verticalAlign: 'middle'}}/></div>
                </div>
                : ""}
                <Toast icon="loading" show={this.state.showLoading}>加载中...</Toast>
            </div>
        )
    }
}